package cn.linstudy.product.controller;

import cn.linstudy.common.utils.R;
import cn.linstudy.product.entity.CategoryEntity;
import cn.linstudy.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;




/**
 * 商品三级分类
 *
 * @author XiaoLin
 * @email ljp2020vip@163.com
 * @date 2023-01-04 14:59:45
 */
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 查询列表，并且以树形结构进行返回
     */
    @RequestMapping("/list")
    public R list(){
        List<CategoryEntity> categoryEntityList = categoryService.listWithTree();
        return R.ok().put("categoryEntityList", categoryEntityList);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{catId}")
    public R info(@PathVariable("catId") Long catId){
		CategoryEntity category = categoryService.getById(catId);

        return R.ok().put("category", category);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody CategoryEntity category){
		categoryService.save(category);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody CategoryEntity category){
        // 级联更新
		categoryService.updateCascade(category);

        return R.ok();
    }

    /**
     * RequestBody请求体，必须发post请求，SpringMVC会自动将请求体数据（JSON），转为对应的对象
     * @param catIds 商品id
     * @return
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] catIds){
        // 检查当前菜单是否被其他地方引用
		categoryService.removeMenusByIds(Arrays.asList(catIds));
        return R.ok();
    }

    /**
     * 批量拖拽修改功能
     * @param category 需要批量拖拽修改的数组分类对象
     * @return
     */
    @RequestMapping("/update/sort")
    public R updateSort(@RequestBody CategoryEntity[] category){
        categoryService.updateBatchById(Arrays.asList(category));
        return R.ok();
    }

}
